package oocl.eshop.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import oocl.eshop.dao.PermissionDao;
import oocl.eshop.po.Permission;
import oocl.eshop.util.dbutil.DbUtil;

public class PermissionDaoImpl implements PermissionDao {

	@Override
	public Permission findPermisson(int mId) {
		Permission permission = null;

		String sql = "select * from permission where mId=? ";
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		con = DbUtil.connect();
		try {
			pst = con.prepareStatement(sql);
			pst.setInt(1, mId);
			rs = pst.executeQuery();
			if (rs.next()) {
				int mStatus = rs.getInt("mStatus");

				permission = new Permission(mId, mStatus);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, null);
		}
		return permission;
	}

	@Override
	public int updatePermisson(Permission p) {
		String sql = "update permission set mStatus=? where mid=?";
		Connection con = null;
		PreparedStatement pst = null;
		con = DbUtil.connect();
		int n = 0;
		try {
			pst = con.prepareStatement(sql);
			con.setAutoCommit(false);
			pst.setInt(1, p.getmStatus());
			pst.setInt(2, p.getmId());
			n = pst.executeUpdate();
			con.commit();
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, null);
		}

		return n;
	}

	@Override
	public int addPermisson(Permission p) {
		String sql = "insert into permission (mId,mStatus)values (?,?)";
		Connection con = null;
		PreparedStatement pst = null;
		con = DbUtil.connect();
		int n = 0;
		try {
			pst = con.prepareStatement(sql);
			pst.setInt(1, p.getmId());
			pst.setInt(2, p.getmStatus());
			n = pst.executeUpdate();
		} catch (SQLException e) {
			System.out.println("添加异常");
			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, null);
		}

		return n;
	}

}
